<template>
    <div class="main">
        <a-card title="景点管理界面" :bordered="false" style="width: 100%; height: 100%;">
            <template #extra>
                <div class="spotEdit">
                    <div class="left">
                        <a-button type="primary" :icon="h(FileAddOutlined)" @click="() => {
                            spotsStore.SetAddOpen(true)
                        }">添加新景点</a-button>
                    </div>
                    <div class="right">
                        <a-button danger type="text" @click="gotoHome" :icon="h(RollbackOutlined)">返回首页</a-button>
                    </div>
                </div>
            </template>
            <a-table :columns="columns" :data-source="data" :scroll="{ x: 400, y: 580 }" :custom-row="handleRowClick"
                :pagination="{ showSizeChanger: true }" bordered>
                <template #headerCell="{ column }">
                    <template v-if="column.key === 'name'">
                        <span style="color: #1890ff">Name</span>
                    </template>
                </template>
                <!-- search -->
                <template #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                    <div style="padding: 8px">
                        <!-- 搜索输入框 -->
                        <a-input ref="searchInput" :placeholder="`Search ${column.dataIndex}`" :value="selectedKeys[0]"
                            style="width: 188px; margin-bottom: 8px; display: block"
                            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)" />
                        <!-- 操作按钮 -->
                        <a-button type="primary" size="small" style="width: 90px; margin-right: 8px"
                            @click="handleSearch(selectedKeys, confirm, column.dataIndex)">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                            Search
                        </a-button>
                        <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
                            Reset
                        </a-button>
                    </div>
                </template>
                <!-- 自定义过滤图标样式，提供视觉反馈。 -->
                <template #customFilterIcon="{ filtered }">
                    <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
                </template>
                <template #bodyCell="{ text, column, record }">
                    <!-- 自定义表格单元格内容，高亮显示匹配搜索关键词的部分。 -->
                    <span v-if="state.searchText && state.searchedColumn === column.dataIndex">
                        <template v-for="(fragment, i) in text
                            .toString()
                            .split(new RegExp(`(?<=${state.searchText})|(?=${state.searchText})`, 'i'))">
                            <mark v-if="fragment.toLowerCase() === state.searchText.toLowerCase()" :key="i"
                                class="highlight">
                                {{ fragment }}
                            </mark>
                            <template v-else>{{ fragment }}</template>
                        </template>
                    </span>
                    <!-- <template v-if="column.key === 'name'">
                        {{ record.name }}
                    </template> -->
                    <!-- 标签 -->
                    <template v-else-if="column.key === 'tags'">
                        <span>
                            <a-tag v-for="tag in record.tags" :key="tag"
                                :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'">
                                {{ tag.toUpperCase() }}
                            </a-tag>
                        </span>
                    </template>
                    <!-- 照片 -->
                    <template v-else-if="column.key === 'photo'">
                        <a-image :src=record.photo />
                    </template>
                    <!-- 评分 -->
                    <template v-else-if="column.key === 'rating'">
                        <a-rate v-model:value=record.rating allow-half />
                    </template>
                    <!-- 操作 -->
                    <template v-else-if="column.key === 'operation'">
                        <div style="margin: 5px;"><a-button type="primary" :icon="h(EditOutlined)" @click="() => {
                            spotsStore.SetEditOpen(true)
                        }">Edit</a-button>
                        </div>
                        <div style="margin: 5px;">
                            <a-popconfirm title="确定要删除该景点信息吗?" ok-text="确认" cancel-text="取消" @confirm="confirm"
                                @cancel="cancel">
                                <a-button type="primary" danger :icon="h(DeleteOutlined)">Delete</a-button>
                            </a-popconfirm>

                        </div>
                    </template>
                </template>
            </a-table>
        </a-card>
        <!-- 引入 EditSpots 组件 -->
        <EditSpots />
        <!-- 引入AddSpots组件 -->
        <AddSpots />
    </div>
</template>
<script setup>

import { watch, ref, onMounted, reactive, h } from 'vue';
import { spotsInfoStore } from '@/stores/spots';
import { SearchOutlined, EditOutlined, DeleteOutlined, FileAddOutlined, RollbackOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { getCityData, delSpots } from '@/api/apitest';
import EditSpots from './EditSpots.vue';
import AddSpots from './AddSpots.vue';
import { useRouter } from 'vue-router';

const router = useRouter()
const onChange = (pagination, filters, sorter) => {
    console.log('params', pagination, filters, sorter);
};
const selectCityName = JSON.parse(localStorage.getItem('cityData'));
getCitySpotsData(selectCityName)
const spotsStore = spotsInfoStore();
const data = ref([]);
let beforetemp = []



//搜索相关变量
const state = reactive({
    searchText: '',
    searchedColumn: '',
});
const searchInput = ref();

const columns = ref([
    {
        title: 'ID',
        key: 'id',
        width: 40,
        dataIndex: 'id',
        fixed: 'left',
    },
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        fixed: 'left',
        customFilterDropdown: true,
        onFilter: (value, record) => record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownOpenChange: visible => {
            if (visible) {
                setTimeout(() => {
                    searchInput.value.focus();
                }, 100);
            }
        },
    },
    {
        title: 'Address',
        dataIndex: 'address',
        width: 100,
        key: 'address',
    },
    {
        title: 'Tags',
        key: 'tags',
        width: 100,
        dataIndex: 'tags',
    },
    {
        title: 'Rating',
        key: 'rating',
        width: 80,
        dataIndex: 'rating',
    },
    {
        title: 'Photo',
        key: 'photo',
        width: 70,
        dataIndex: 'photo',
    },
    {
        title: 'Comments',
        key: 'comment',
        width: 100,
        dataIndex: 'comment',
    },
    {
        title: 'Tel',
        key: 'tel',
        width: 70,
        dataIndex: 'tel',
    },
    {
        title: 'Operation',
        key: 'operation',
        width: 100,
        dataIndex: 'operation',
        fixed: 'right',
    }
])

//路由跳转函数
const gotoHome = () => {
    router.push('/')
}

//获取城市景点数据
async function getCitySpotsData(cityname) {
    const data = await getCityData(cityname)
    spotsStore.SetcityData(data.data)
    spotsStore.SettempData(data.data)
    localStorage.setItem('cityData', JSON.stringify(cityname))
    // console.log(spotsStore.cityData, 'cityData');
    // console.log(data)
}
//删除景点数据
const DelSpots = async () => {

}
//删除确认事件
const confirm = async () => {
    console.log(spotsStore.selectedSpot[0].id);

    await delSpots(spotsStore.selectedSpot[0].id)
    // 更新数据
    spotsStore.SetcityData(spotsStore.tempData.filter(spot => spot.id !== spotsStore.selectedSpot[0].id)); // 更新 cityData中修改数据
    spotsStore.SettempData(spotsStore.tempData.filter(spot => spot.id !== spotsStore.selectedSpot[0].id)); // 更新 tempData中修改数据
    message.success('删除信息成功');
};
//删除取消事件
const cancel = e => {
    message.error('删除操作取消');
};
// 更新景点信息
const updatePlaces = (citydata) => {
    const updatedData = [];
    for (let i = 0; i < citydata.length; i++) {
        updatedData.push({
            key: i + 1,
            photo: citydata[i].photos[0],
            name: citydata[i].spotname,
            address: citydata[i].address,
            tags: citydata[i].type.split(';'),
            rating: citydata[i].rating,
            tel: citydata[i].tel,
            id: i + 1,
            comment: citydata[i].comment,
        });
    }
    data.value = updatedData;
};

// 处理行点击事件
const handleRowClick = (record) => {
    return {
        onClick: () => {
            // spotsStore.tempData.filter((item) => item.spotname.includes(record.name))
            //点击一行后将数据送到编辑界面
            spotsStore.SetSelectedSpot(spotsStore.tempData.filter((item) => item.spotname.includes(record.name)));
            console.log(spotsStore.tempData.filter((item) => item.spotname.includes(record.name)));
            console.log(spotsStore.selectedSpot[0], '131313');
        }
    };
};

// 搜索相关方法
const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    //更新获取数据
    beforetemp = spotsStore.tempData
    if (selectedKeys.length === 0) {
        message.error('请输入搜索内容');
        return;
    }
    console.log(beforetemp.filter((item) => item.spotname.includes(selectedKeys[0])));

    if (beforetemp.filter((item) => item.spotname.includes(selectedKeys[0])).length === 0) {
        message.error('未找到相关景点');
        return;
    }
    console.log(selectedKeys, dataIndex);
    state.searchText = selectedKeys[0];
    state.searchedColumn = dataIndex;

    // 地图上的景点信息更新
    spotsStore.SetcityData(spotsStore.cityData.filter((item) => item.spotname.includes(selectedKeys[0])));
    console.log(spotsStore.cityData, 'spotsStore.cityData', beforetemp, 'temp');

};
const handleReset = clearFilters => {
    clearFilters({
        confirm: true,
    });
    state.searchText = '';
    spotsStore.SetcityData(beforetemp);
};

// Lifecycle hook
onMounted(() => {
    const test = JSON.parse(localStorage.getItem('cityData'))
    // console.log(test, '111111');
    getCitySpotsData(test)
    updatePlaces(spotsStore.cityData);
});

watch(() => spotsStore.cityData, (newCityData) => {
    updatePlaces(newCityData);
    // console.log(newCityData, 'spotsStore.cityData');
}, { deep: true });

</script>
<style lang="scss" scoped>
.spotEdit {
    display: flex;

    .left {
        margin-right: 20px;
    }
}

.main {
    background: #ececec;
    padding: 30px;
    width: 100%;
    height: 100vh;

    .PlacesView {
        width: 100%;
        height: 100%;
    }

    .highlight {
        background-color: rgb(255, 192, 105);
        padding: 0px;
    }
}
</style>